package controller

import (
	"KD_web/go/entity"
	"KD_web/go/errors"
	"KD_web/go/service"
	"github.com/gin-gonic/gin"
	"net/http"
)

func CreateComment(c *gin.Context) {
	var comment entity.Comment
	if err := c.BindJSON(&comment); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 4004, "msg": "Invalid input!"})
		return
	}

	err := service.GenerateComment(&comment)
	if err != nil {
		if customErr, ok := err.(*errors.CustomError); ok {
			c.JSON(HttpStatusForErrorCode(customErr.Code), customErr)
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1000, "msg": "Unknown error"})
		}
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"msg":     "success",
		"comment": comment.Comment,
	})
}

func GetCommentByTableId(c *gin.Context) {
	// 这里id是指table表的Id
	id := c.Param("id")
	comment, err := service.GetCommentByTableId(id)
	if err != nil {
		if customErr, ok := err.(*errors.CustomError); ok {
			c.JSON(HttpStatusForErrorCode(customErr.Code), customErr)
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 1000, "msg": "Unknown error"})
		}
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"msg":     "success",
			"comment": comment,
		})
	}
}
